﻿using AutoMapper;
using Finance.Api.Write.Applications.Commands.财务管理.Refunds;
using Finance.Domain;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;
using System.Security.Claims;

namespace Finance.Api.Write.Applications.CommandHands.财务管理.Refunds
{
    public class RefundAddCommandHandler : IRequestHandler<RefundAddCommand, ApiResult<int>>
    {
        private readonly SqlsugarDb<Refund> db;
        private readonly IMapper mapper;
        private readonly IHttpContextAccessor httpContextAccessor;

        public RefundAddCommandHandler(SqlsugarDb<Refund> db, IMapper mapper, IHttpContextAccessor httpContextAccessor)
        {
            this.db = db;
            this.mapper = mapper;
            this.httpContextAccessor = httpContextAccessor;
        }

        public async Task<ApiResult<int>> Handle(RefundAddCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();
            try
            {
                if (request.SupplierId==0)
                { 
                
                        result.Code=Enumcode.Nonull;
                    result.message = "供应商名称不能为空";
                   
                    return result;
                    
                }
                var AddResult = mapper.Map<Refund>(request);
                AddResult.CreateTime = DateTime.Now;
                AddResult.CreateName = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Name)?.Value;
                AddResult.LoginId = Convert.ToInt32(httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
                
               var Insert=  await db.AddAsync(AddResult);
                if (Insert > 0)
                {
                    result.message = "添加成功";
                    result.data = 1;
                    result.Code = Enumcode.ok;
                }
                else
                {
                    result.message = "添加失败";
                    result.data = 1;
                    result.Code = Enumcode.fail;
                }

            }
            catch (Exception ex)
            {

                result.message =ex.Message;
                result.data = 1;
                result.Code = Enumcode.fail;
            }

            return await Task.FromResult(result);

            
        }
    }
}
